Home:ALL Converter>Scala How can Trait override toString Case Class that is Derived Off

Scala How can Trait override toString Case Class that is Derived Off

Ask Time:2020-02-24T01:09:43         Author:Greedo

Json Formatter

My background is in C++/C and I am trying to learn scala. I am struggling to understand how a trait's toString method overrides case class derived from the trait. Surely the default case class's toString method should over ride the trait's? I am missing something obvious?

Code

trait Computer {
  def ram: String
  def hdd: String
  def cpu: String

  override def toString = "RAM= " + ram + ", HDD=" + hdd + ", CPU=" + cpu

}

private case class PC(ram: String, hdd: String, cpu: String) extends Computer 

private case class Server(ram: String, hdd: String, cpu: String) extends Computer

object ComputerFactory {
  def apply(compType: String, ram: String, hdd: String, cpu: String) = compType.toUpperCase match {
    case "PC" => PC(ram, hdd, cpu)
    case "SERVER" => Server(ram, hdd, cpu)
  }
}
val pc = ComputerFactory("pc", "2 GB", "500 GB", "2.4 GHz");
val server = ComputerFactory("server", "16 GB", "1 TB", "2.9 GHz");

println("Factory PC Config::" + pc);
println("Factory Server Config::" + server);

Author:Greedo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60364713/scala-how-can-trait-override-tostring-case-class-that-is-derived-off
yy